import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from calculate import process_interpolation_data
from scipy.interpolate import interp1d

# 文件路径和数据加载
root_path = 'E:/福建数据/spar/04/test1/'
filename_ZH = 'Z_RADR_I_Z9600_20240430024720_O_DOR_PAR-SD_CAP_025.bin.gz_ZH.csv'
filename_CC = 'Z_RADR_I_Z9600_20240430024720_O_DOR_PAR-SD_CAP_025.bin.gz_CC.csv'

data = process_interpolation_data(root_path, filename_ZH, filename_CC)  # 示例数据，真实数据请替换

# 已知的层和目标层
known_elevations = np.array([0.5, 1.45, 2.4])  # 已知层的仰角
target_elevation = 0.89  # 目标层的仰角
known_layers = [0, 2, 3]  # 已知的层索引
target_layer = 1  # 目标插值的层索引

data[data == -32768] = np.nan

interpolated_data = np.full((78, 3879), np.nan)  # 初始化插值结果
for i in range(78):  # 遍历方位角
    for j in range(3879):  # 遍历距离库
        # 提取已知层的数据
        values = data[known_layers, i, j]
        valid_mask = ~np.isnan(values)  # 筛选有效值
        if np.sum(valid_mask) >= 2:  # 至少需要两个有效值进行插值
            interp_func = interp1d(
                known_elevations[valid_mask],
                values[valid_mask],
                kind="linear",
                bounds_error=False,
                fill_value="extrapolate",
            )
            interpolated_data[i, j] = interp_func(target_elevation)

# 真实数据
true_data = data[target_layer, :, :]

# 计算误差（忽略 NaN）
valid_mask = ~np.isnan(true_data) & ~np.isnan(interpolated_data)
mse = mean_squared_error(true_data[valid_mask], interpolated_data[valid_mask])
correlation_matrix = np.corrcoef(true_data[valid_mask], interpolated_data[valid_mask])
correlation = correlation_matrix[0, 1]  # 取非对角线元素

print(f"均方误差 (MSE): {mse:.4f}")
print(f"相关系数 (R): {correlation:.4f}")
# print(f"均方误差 (MSE): {mse:.4f}")

# 散点图和 KDE 绘制
plt.figure(figsize=(10, 6))

# 散点图
plt.scatter(
    interpolated_data[valid_mask],
    true_data[valid_mask],
    alpha=0.5,
    s=5,
    label="Data Points",
)

# 1:1 对角线
max_val = max(np.nanmax(interpolated_data), np.nanmax(true_data))
min_val = min(np.nanmin(interpolated_data), np.nanmin(true_data))
plt.plot([min_val, max_val], [min_val, max_val], color="red", linestyle="--", label="1:1 Line")

# KDE 图
sns.kdeplot(
    x=interpolated_data[valid_mask],
    y=true_data[valid_mask],
    cmap="Blues",
    fill=True,
    alpha=0.5,
    label="KDE Density",
)

# 图例和标题
plt.title("Comparison of Interpolated vs True Data (With Missing Values)", fontsize=14)
plt.xlabel("Interpolated Data", fontsize=12)
plt.ylabel("True Data", fontsize=12)
plt.legend(fontsize=12)
plt.grid(True)
plt.show()
